package com.hujia.service;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;

import com.hujia.entity.Area;
import com.hujia.entity.City;
import com.hujia.rs.redis.RedisProvider;

import io.vertx.core.Future;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.redis.RedisClient;

public class CityService {
	
	/**
	 * 加载城数据
	 * @return
	 */
	public Future<Void> loadCityData() {
		Future<Void> future = Future.future();
		InputStream is = null;
		try {
			is = City.class.getClassLoader().getResourceAsStream("cities.json");
			String cityData = IOUtils.toString(is, StandardCharsets.UTF_8);
			JsonArray citys = new JsonArray(cityData);
			if (citys == null || citys.isEmpty()) {
				future.fail("城市数据读取失败");
			}

			// 存一个region的key
			// 存一个城市的有序集合, key="province-"+省份的code
			JsonObject regions = new JsonObject();
			Map<String,List<String>> cityMap = new HashMap<String,List<String>>();

			for (int i = 0; i < citys.size(); i++) {
				JsonObject jsonObject = citys.getJsonObject(i);
				String code = jsonObject.getString("code");
				regions.put(String.format("region-%s", code), jsonObject.toString());
				String provinceKey = String.format("province-%s", jsonObject.getString("provinceCode"));
				
				List<String> cityList = cityMap.get(provinceKey);
				if (cityList == null) {
					cityList = new ArrayList<String>();
					cityMap.put(provinceKey, cityList);
				}
				
				cityList.add(code);
			}

			RedisClient redisClient = RedisProvider.getRedisClient();
			redisClient.mset(regions, msetRes -> {
				if (msetRes.succeeded()) {
					Iterator<String> keys = cityMap.keySet().iterator();
					while(keys.hasNext()) {
						String key = keys.next();
						List<String> value = cityMap.get(key);
						
						redisClient.del(key, rss -> {
							if (rss.succeeded()) {
								redisClient.saddMany(key, value, rs -> {
									if (rs.failed()) {
										System.out.println("加载城市数据失败.");
										future.fail(rs.cause().getMessage());
									}
									
								});
							}
						});
						
						
					}
					System.out.println("加载城市数据完成.");
					future.complete();
				}
			});
		}catch(Exception ex) {
			future.fail(ex.getMessage());
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}	
		}
		
		return future;
	}
	
	/**
	 * 获取区域的子节点
	 */
	public Future<List<Area>> children(String cityCode) {
		Future<List<Area>> future = Future.future();
		
		RedisClient redisClient = RedisProvider.getRedisClient();
		String key = String.format("city-%s", cityCode);
		
		redisClient.smembers(key, rs-> {
			
			if (rs.failed()) {
				future.fail(rs.cause().getMessage());
				return;
			}
			
			JsonArray jsonArray = rs.result();
			List<String> keys = new ArrayList<String>();
			for (int i=0;i< jsonArray.size() ;i++) {
				keys.add(String.format("region-%s", jsonArray.getString(i)));
			}
			
			redisClient.mgetMany(keys, rss-> {
				if (rss.failed()) {
					future.fail(rs.cause().getMessage());
					return;
				}
				
				JsonArray areaJsonArray = rss.result();
				if (areaJsonArray == null || areaJsonArray.isEmpty()) {
					future.fail("获取失败.");
					return;
				}
				
				List<Area> areas = new ArrayList<Area>();
				for (int i = 0; i < areaJsonArray.size(); i++) {
					Area area = new Area();
					try {
						 JsonObject jsonObject = new JsonObject(areaJsonArray.getString(i));
						 area.scan(jsonObject);
					} catch (Exception e) {
						e.printStackTrace();
						future.fail(e.getMessage());
						return;
					}
					areas.add(area);
				}
				future.complete(areas);
			});
		});
		
		return future;
	}
	
	
	
	
}
